package cn.springstudio.springui.template;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.springstudio.springui.databinding.LayoutGridBinding;

public abstract class GridFragment extends Fragment implements GridAdapter.OnGridListener {

    GridAdapter adapter;
    LayoutGridBinding binding;
    List<String> data = new ArrayList<>();
    Map<String, Class<?>> classMap = new LinkedHashMap<>();

    public GridFragment() {
    }

    protected void addAction(@NonNull String name, @NonNull Class<?> cls) {
        data.add(name);
        classMap.put(name, cls);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (binding == null) {
            binding = LayoutGridBinding.inflate(inflater);
        }
        if (adapter == null) {
            adapter = new GridAdapter(requireContext(), this);
        }
        binding.recyclerView.setAdapter(adapter);
        return binding.getRoot();
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public String getItem(int position) {
        return data.get(position);
    }

    @Override
    public void onItemClicked(int position) {
        startActivity(new Intent(requireContext(), classMap.get(getItem(position))));
    }
}